import React, { useState, useMemo, useEffect } from 'react';
import { cline, Ret, Title, useHigh, GridTable, useCmd, WaitUmd, MainView, KFind, useKForm, obj_str, PanelTitle,
     for_obj, to_float, ck_empty, d_sort, save_xlsx, obj_int, obj_str_trim, uDb, Btn, is_empty, loc } from 'sui';
import { get_col, face_list, load_ball } from './cmd';

const NgView = ({ mod, data, title, hreturn, col, map_ng, map_stuff, map_supply }) => {
    const [lst_ball, lstBall] = useState();
    const [row, setRow] = useState();
    const [sum, setSum] = useState([]);
    const [high] = useHigh(220, 100);
    const umd = useCmd();
    const form = useKForm();

    useEffect(() => load_ball(lstBall), []);

    const techList = useMemo(() => {
        if (is_empty(data)) {
            return null;
        }

        const set = new Set();
        const ret = [];

        data.forEach(d => {
            const tech = obj_str_trim(d, "sn");
            if (set.has(tech)) {
                return;
            }

            ret.push({ sn: "" + tech, name: tech });
            set.add(tech);
        });

        d_sort(ret, "sn");

        return ret;
    }, [data]);

    const hfind = () => {
        const ck = {
            tech : v => ck_empty(v),
            ball : v => ck_empty(v),
        };

        if (mod === "seal") {
            ck["face"] = (v) => ck_empty(v);
        }

        if (form.isErr(ck)) {
            return;
        }

        const tech = form.get("tech");
        const face = form.get("face");
        const ball = "" + to_float(form.get("ball"));

        umd.startWait();

        uDb(null, `file/list/de${mod}`, { line: cline() },
            r => {
                const ret = [];
                const ng_son = {};
                let dnum_all = 0;

                r.forEach(d => {
                    const t_dnum = obj_int(d, "num");
                    const t_tech = obj_str_trim(d, "tech");
                    const t_ball = obj_str_trim(d, "ball");
                    const t_face = obj_str_trim(d, "face");

                    if (t_face !== face || t_ball !== ball || t_tech !== tech || t_dnum <= 0) {
                        return;
                    }

                    const t_ngson = obj_str_trim(d, "ngson");

                    if (ng_son[t_ngson]) {
                        ng_son[t_ngson] += t_dnum;
                    } else {
                        ng_son[t_ngson] = t_dnum;
                    }

                    dnum_all += t_dnum;

                    ret.push(d);
                });

                d_sort(ret, "sn");

                ret.forEach((d, i) => d["index"] = i + 1);

                setRow(ret);

                const sum_row = [{ index: loc("l_595"), num: dnum_all}];

                for_obj(ng_son, (k, v) => {
                    let ks = k;

                    if (map_ng) {
                        ks = map_ng[k];
                        if (!ks) {
                            ks = k;
                        }
                    }

                    sum_row.push({
                        index: ks,
                        num: v,
                    });
                });

                setSum(sum_row);

                umd.endWait();
            },
            e => {
                setRow(null);
                setSum(null);
                umd.endWait();
            });
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 120, frozen: true, summaryFormatter: ({ row }) => <strong>{obj_str(row, "index")}</strong>},
            {name: loc("l_127"), key: 'num', width: 120, frozen: true, summaryFormatter: ({ row }) => <strong>{obj_str(row, "num")}</strong>},
            {name: loc("l_811"), key: 'ngson', width: 120, frozen: true,
                formatter: props => {
                    let sn = obj_str(props.row, "ngson");

                    const tmp = obj_str(map_ng, sn);
                    if (tmp) {
                        sn = tmp;
                    }

                    return sn;
                },
                summaryFormatter: ({ row }) => <strong>{obj_str(row, "num")}</strong>},
        ];

        get_col(col, tmp, map_supply, map_stuff, map_ng, true, true);

        return tmp;
    };

    const hExport = () => {
        umd.startWait();

        const col_cen = getCol();
        if (is_empty(col_cen) || is_empty(row)) {
            umd.setErr(loc("l_276"));
        }

        const col_c = [];
        const h = [];

        col_cen.forEach(d => {
            h.push({ value: d.name });
            col_c.push(d.key);
        });

        const out = [h];

        row.forEach(d => {
            const tmp = [];
            col_c.forEach(t => tmp.push({ value: obj_str(d, t) }));

            out.push(tmp);
        });

        if (!is_empty(sum)) {
            out.push([{ value: "" }]);

            sum.forEach(d => {
                out.push([
                    { value: d["index"] },
                    { value: d["stock"] },
                ]);
            });
        }

        save_xlsx(out, `${title}_${loc("l_813")}_${form.get("tech")}.xlsx`, umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={hExport} className="mr-4">{loc("l_519")}</Btn>
            <Ret hcmd={hreturn}/>
        </div>
    );

    const getFace = () => {
        if (mod === "seal") {
            return <KFind label={`AB ${loc("l_814")}`} form={form} name="face" margin="dense" width="w-56" list={face_list()} className="ml-4"/>;
        }

        return null;
    };

    return (
        <MainView>
            <PanelTitle left={<Title mod={loc("l_813")} sub={title}/>} right={<Right/>} cl="gray">
                <div className="flex items-center mb-1 justify-between">
                    <div className="inline-flex">
                        <Btn hcmd={() => hfind()} color="green" className="mr-4">{loc("l_332")}</Btn>
                        <KFind label={loc("l_363")} form={form} name="tech" margin="dense" width="w-56" list={techList}/>
                        <KFind label={loc("l_714")} form={form} name="ball" margin="dense" width="w-56" list={lst_ball} className="ml-4"/>
                        {getFace()}
                    </div>
                </div>
            </PanelTitle>
            <GridTable col={getCol()} row={row} high={high} sumrow={sum}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {NgView};
